#include "ebm_env.h"
#include "bconn.h"
#include "nstar_ts_pack.h"


static struct bsockt ebm_cmdNet_handle = \
BCONN_INIT_STRUCTURE("ebm Cmd", 0, 0, 0, DEFAULT_TR_OUT);


static void _cmdRec(struct bsockt *b)
{
    unsigned char data[512]; unsigned short dlen = 512;
    //if(PEND_T_R())
    int len = bconn_rec(b, data, dlen);
    if(len) {
        //printf("%s rec %d bytes\n", b->name, len);
        nstar_parse_msg(data, len);
    } 
}

static void _cmdSend_loadbytes(int fd)
{
    unsigned char buf[20];
    unsigned char len= nstar_pack_loadbytes(buf, 20, 0);
    write(fd, buf, len);   
}

static void _cmdSend(struct bsockt *b)
{
    unsigned char *data; unsigned int len;
    if(PEND_T_S()){
        unsigned short ticks = adpEnv_get_heart_tp();
        //data = nstar_ts_pack_get_snd_dta(&len);
        //bconn_send(b, data, len);
       
        SLEPP_T_S(ticks);  
    }
}

void ebm_cmdNet_start(void) {
    bconn_connect(&ebm_cmdNet_handle, ebmEnv_get_sip(), ebmEnv_get_plat_port());
}

void ebm_cmdNet_stop(void)
{
    bconn_stop(&ebm_cmdNet_handle);
}

void ebm_cmdNet_restart(void)
{
    bconn_restart(&ebm_cmdNet_handle);
}

void *ebm_cmd_task(void *parm)
{
    struct bsockt *b = &ebm_cmdNet_handle;
    nstar_ts_pack_init();
    ebm_cmdNet_start();
    bconn_reg_LoadFuc(b, _cmdSend_loadbytes);
	while(1)
	{
		bconn_machine(b);
        if(bconn_isConnect(b)) {
            _cmdRec(b);
            _cmdSend(b);
        }
        usleep(10*1000);
	}
	return 0;
}

unsigned char ebm_cmdNet_sta(void)
{
    struct bsockt *b = &ebm_cmdNet_handle;
    return bconn_isConnect(b);
}

const char* ebm_cmdNet_stastr(void)
{
    const char* str[] = {
        "未连接",
        "正常" 
    };
    unsigned char sel = ebm_cmdNet_sta();
    sel = MIN(1, sel);
    return str[sel];
}

unsigned int ebm_cmdNet_speed(void)
{
    /*发送速率*/
    struct bsockt *b = &ebm_cmdNet_handle;
    return bconn_speed_s(b);
}





